package com.simon.app.october.modules.sys.service.impl;

import com.simon.app.october.common.utils.PageUtil;
import com.simon.app.october.common.utils.QueryPage;
import com.simon.app.october.common.utils.Result;
import com.simon.app.october.common.validator.ValidatorUtils;
import com.simon.app.october.modules.sys.dao.SysRoleDao;
import com.simon.app.october.modules.sys.entity.SysRoleEntity;
import com.simon.app.october.modules.sys.service.SysRoleMenuService;
import com.simon.app.october.modules.sys.service.SysRoleService;
import com.simon.app.october.modules.sys.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleDao roleDao;

    @Autowired
    private SysRoleMenuService roleMenuService;

    @Autowired
    private SysUserRoleService userRoleService;

    @Override
    public List<SysRoleEntity> getList() {
        return roleDao.getList();
    }

    @Override
    public PageUtil listPage(Map<String, Object> params) {
        params = new QueryPage(params);

        int page  = (int) params.get("page");
        int limit = (int) params.get("limit");
        int total = roleDao.getTotal(params);
        List<SysRoleEntity> list = roleDao.listPage(params);
        int pageNum = (int) Math.ceil(total/(double)limit);

        PageUtil<SysRoleEntity> pageUtil = new PageUtil<>();
        pageUtil.setList(list);
        pageUtil.setPageSize(limit);
        pageUtil.setCurrPage(page);
        pageUtil.setTotalPage(pageNum);
        pageUtil.setTotalCount(total);
        return pageUtil;
    }

    @Override
    public SysRoleEntity findById(int id) {
        SysRoleEntity roleEntity = roleDao.findById(id);

        // 查出相关的菜单id
        roleEntity.setMenuIdList(roleMenuService.getMenuIdsByRoleId((long)id));
        return roleEntity;
    }

    @Override
    public void save(SysRoleEntity role) {
        // 插入角色
        roleDao.insert(role);

        // 处理角色关联的菜单
        if (0 == role.getMenuIdList().size()) {
            return ;
        }
        roleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
    }

    @Override
    public void updateById(SysRoleEntity role) {
        // 更新基础信息
        roleDao.updateById(role);
    }

    @Override
    public void update(SysRoleEntity role) {
        // 更新角色对应的菜单
        this.updateById(role);

        // 更新角色对应的菜单
        roleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
    }

    @Override
    public void delete(Long[] ids) {
        List<Long> roleIds = Arrays.asList(ids);
        // 删除角色
        roleDao.deleteByIds(roleIds);

        // 删除角色与菜单的关连
        roleMenuService.deleteByRoleIds(ids);

        // 删除角色与用户的关联
        userRoleService.deleteByRoleIds(ids);
    }
}
